#include "sem.h"
#include "list.h"
#include "task.h"  // ??????
#include <stddef.h>
// ??? extern ??,??????? task.h

void sem_init(sem_t *sem, int sem_count)
{
    sem->count = sem_count;
    list_init(&sem->wait_list);
}

void sem_get(sem_t *sem)
{
    __disable_irq();
    if(sem->count > 0)
    {
        sem->count--;
        __enable_irq();
    }
    else
    {
        tcb *current = &tasks[cur_task];
        current->state = TASK_STATE_BLOCKED;
        
        list_remove(&ready_list[current->priority], &current->node);

        list_add_tail(&sem->wait_list, &current->node);
        __enable_irq();
    }
}

void sem_post(sem_t *sem)  
{
    __disable_irq();
    sem->count++;
    
    if (!list_empty(&sem->wait_list)) {
        list_node_t *node = list_remove_head(&sem->wait_list);
        tcb *task = (tcb *)((char *)node - offsetof(tcb, node));
        task->state = TASK_STATE_READY;
        task_add_to_ready(task);  
    }
    
    __enable_irq();
}